package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    private static HttpServletResponse token;

    public static void setToken(HttpServletResponse resp,String key,String value,int time) {
        //4:将token送到浏览器中
        Cookie cookie = new Cookie(key, value);
        //4.1: 设置cookie共享路径
        cookie.setPath("/");
        //4.2: 设置cookie有效时间
        cookie.setMaxAge(time);
        resp.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest req,HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        //判断cookie
        if (cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                //判断存储的key值是否对相应
                if ("token".equals(cookie.getName())) {
                    //存在设置最大存活时间
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    //设置作用域
                    cookie.setPath("/");
                    //在响应给浏览器
                    resp.addCookie(cookie);
                    //返回redis中存储的key值
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
